/*     Copyright (c) 2018, jymenu.com. All rights reserved.   */
package com.yunhaikeji.core.util;

import java.security.SecureRandom;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * IdUtils
 *
 * @author : zhuo
 * @date : 2018/8/7 20:16
 * @description :
 */
public class IdUtils {
    private static SecureRandom random = new SecureRandom();
    private static AtomicInteger localAutoIncrement = new AtomicInteger(0);
    private static final int SERVER_ID = 1;
    private static final int MAX_ID = (1 << 16) - 1;

    /**
     * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.
     */
    public static String uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 使用SecureRandom随机生成Long.
     */
    public static long randomLong() {
        return Math.abs(random.nextLong());
    }

    public static String ranomNumber(int length) {
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++){
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    /**
     * 基于Base62编码的SecureRandom随机生成bytes.
     */
    public static String randomBase62(int length) {
        byte[] randomBytes = new byte[length];
        random.nextBytes(randomBytes);
        return EncodeUtils.encodeBase62(randomBytes);
    }

    /**
     * 获取递增的long
     * @return
     */
    public static long incrementLong(){
        long current = System.currentTimeMillis();
        int local = localAutoIncrement.getAndUpdate((pre) -> pre == MAX_ID ? 0 : ++pre);
        current = current << 22;
        local = local << 16;
        return current | local | SERVER_ID;
    }
}
